//
//  AppDelegate.swift
//  SwiftProject
//
//  Created by qindong on 2021/3/3.
//

import UIKit

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window : UIWindow?
    // 解决跳到第三方app后返回 会请求失败问题
    var taskId : UIBackgroundTaskIdentifier?
    var timer : Timer?
    
    // 由于Appdelegate是项目入口类很多第三方（zhifu，分享，推送等）都会在这初始化，所以给appdelegate减负 用组合模式解耦
    let appDelegateFactory = AppDelegateFactory.makeDefault()
    enum AppDelegateFactory {
        static func makeDefault() -> AppDelegateType {
            CompositeAppDelegate(appDelegates: [
                PushNotificationsAppDelegate()
                ]
            )
        }
    }
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        NothingToSeeHere.harmlessFunction()
        _ = appDelegateFactory.application?(application, didFinishLaunchingWithOptions: launchOptions)
        _ = YHBaseConfiguration.shared
        do {
            try FileManager.default.removeItem(atPath: NSHomeDirectory() + "/Library/SplashBoard")
        } catch {
            print("Failed to delete launch screen cache: \(error)");
        }
//MARK: -  因iOS13 ipad添加了多窗口模式 在plist-Application Scene Manifest里配置UISceneSession情况下 要去SceneDelegete里 管理生命周期 否则就在AppDelegate里管理
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.backgroundColor = .white
        if GuideViewController.showGuideView() {
            window?.rootViewController = GuideViewController()
        } else {
            if BaseUserModel.unarchiver() != nil {
                window?.rootViewController = TabbarController()
            } else {
                let nav = QMUINavigationController(rootViewController: LoginViewController())
                window?.rootViewController = nav
            }
        }
        window?.makeKeyAndVisible()
        
        // rxswift 注册代理
        RxImagePickerDelegateProxy.register { (p) -> RxImagePickerDelegateProxy in
            RxImagePickerDelegateProxy(imagePicker: p)
        }
        
        YHBaseConfiguration.shared.requestConfig()
        BaseUserModel.refreshUserInfo {
            
        }
//        showAdImage()
//        GuideView.showGuideView()
        return true
    }
    
    // MARK:- 启动页之后的广告页管理器
    func showAdImage() {
        LaunchScreenManager.shared.showLaunchAnimationView()
    }
    
    static var appDelegate : AppDelegate {
        UIApplication.shared.delegate as! AppDelegate
    }


    // MARK:- UISceneSession Lifecycle iOS13 新增UISceneSession代替UIApplication来管理生命周期
//    @available(iOS 13.0, *)
//    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
//        // Called when a new scene session is being created.
//        // Use this method to select a configuration to create the new scene with.
//        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
//    }
//
//    @available(iOS 13.0, *)
//    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
//        // Called when the user discards a scene session.
//        // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
//        // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
//    }
    
    func applicationDidEnterBackground(_ application: UIApplication) {
        appDelegateFactory.applicationDidEnterBackground?(application)
        if taskId != .invalid { return }
        taskId = application.beginBackgroundTask(expirationHandler: {
            self.endTask()
        })
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(longTimeTask(timer:)), userInfo: nil, repeats: true)
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = (touches as NSSet).anyObject() as AnyObject
        if touch.location(in: nil).y <= StatusBarHeight {
            CustomRelay.manager.statusBarClickPublishRelay.accept(true)
        }
    }
    
    @objc func longTimeTask(timer : Timer) {
        let time : TimeInterval = UIApplication.shared.backgroundTimeRemaining
        print("系统留给的我们的时间 = \(time) Seconds")
    }
    
    func endTask() {
        if timer != nil || (timer?.isValid) != nil {
            timer?.invalidate()
            timer = nil
            UIApplication.shared.endBackgroundTask(taskId!)
            taskId = .invalid
            print("停止计时")
        }
    }
}

extension UIApplication {
    // 获取当前有效window
    @available(iOS 13.0, *)
    var currentWindow: UIWindow? {
        if connectedScenes.count > 0 {
           return connectedScenes
            .filter({$0.activationState == .foregroundActive})
            .map({$0 as? UIWindowScene})
            .compactMap({$0})
            .first?.windows
            .filter({$0.isKeyWindow}).first
        } else {
            return AppDelegate.appDelegate.window
        }
    }
}

